﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Common;
using System.Text;
using System.Linq;

public class Message
{
    //存读取到的数据用的数组
    private byte[] data = new byte[1024];
    //在数组中开始存数据的索引
    //在数组中存取了多少字节的数据
    private int startIndex = 0;

    public byte[] Data
    {
        get { return data; }
    }

    public int StartIndex
    {
        get { return startIndex; }
    }

    /// <summary>
    /// 剩余长度
    /// </summary>
    public int ReaminSize
    {
        get { return data.Length - startIndex; }
    }

    /// <summary>
    /// 添加数据
    /// </summary>
    /// <param name="count"></param>
    //public void AddCount(int count)
    //{
    //    startIndex += count;
    //}

    /// <summary>
    /// 读取数据/解析数据
    /// </summary>
    public void ReadMessage(int newDataAmout, Action<ActionCode, string> processDataCallback = null)
    {
        startIndex += newDataAmout;
        while (true)
        {
            //判断最小的数据长度
            if (startIndex <= 4)
                return;
            //解析数据长度
            int count = BitConverter.ToInt32(data, 0);
            //读取剩余数据
            if ((startIndex - 4) >= count)//当前消息是完整的
            {
                //string s = Encoding.UTF8.GetString(data, 4, count);
                //Console.WriteLine("解析出来一条数据:" + s);

                //RequestCode requestCode = (RequestCode)BitConverter.ToInt32(data, 4);
                ActionCode actionCode = (ActionCode)BitConverter.ToInt32(data, 4);
                string s = Encoding.UTF8.GetString(data, 8, count - 4);
                processDataCallback(actionCode, s);
                Array.Copy(data, count + 4, data, 0, startIndex - count - 4);
                startIndex -= (count + 4);
            }
            else
            {
                break;
            }
        }
    }

    /// <summary>
    /// 包装数据
    /// 数据长度+requestcode长度+数据
    /// </summary>
    /// <param name="requestCode"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public static byte[] PackData(RequestCode requestCode, ActionCode actionCode, string data)
    {
        byte[] requestCodeBytes = BitConverter.GetBytes((int)requestCode);
        byte[] actionCodeBytes = BitConverter.GetBytes((int)actionCode);
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        int dataAmount = requestCodeBytes.Length + dataBytes.Length + actionCodeBytes.Length;
        byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);
        //byte[] newBytes = dataAmountBytes.Concat(requestCodeBytes).ToArray<byte>();//Concat(dataBytes);
        //return newBytes.Concat(dataBytes).ToArray<byte>();
        return dataAmountBytes.Concat(requestCodeBytes).ToArray<byte>()
            .Concat(actionCodeBytes).ToArray<byte>()
            .Concat(dataBytes).ToArray<byte>();
    }
}
